//
//  RentHouseDetailViewController.m
//  House
//
//  Created by 张垚 on 16/7/19.
//  Copyright © 2016年 ZJWL. All rights reserved.
//

#import "RentHouseDetailViewController.h"
#import "BaseTitleNavigationBar.h"
#import "ImageViewAndLabelButton.h"
#import "RecycleViewCollectionViewCell.h"
#import "IndexMainRecommondTableViewCell.h"
#import "ReuseHouseBaseInfoTableViewCell.h"
#import "ReuseCategoryChooseTableViewCell.h"
#import "HouseEvaluateTableViewCell.h"
#import "UnfoldFrameModel.h"
#import "UnfoldModel.h"
#import "NearMapViewController.h"
#import "HouseEvaluateInfoViewController.h"
#import "IndoorMatchTableViewCell.h"
#import "SecondaryHouseDetailTableViewCell.h"
#import "RentHouseDetailModel.h"
#import <UMSocial.h>
#import "House-Swift.h"
#import "SecondaryHouseListNoSlideTableViewCell.h"
#import "SDPhotoBrowser.h"
#import "HouseDetailCharacteristicTableViewCell.h"

@interface RentHouseDetailViewController ()<UITableViewDelegate, UITableViewDataSource, HouseEvaluateTableViewCellDelegate, UMSocialUIDelegate, SDCycleScrollViewDelegate, SDPhotoBrowserDelegate>
//顶部视图
@property (nonatomic, strong) BaseTitleNavigationBar *myBar;
//关注、分享、咨询三个按钮
@property (nonatomic, strong) ImageViewAndLabelButton *attentionButton;
@property (nonatomic, strong) ImageViewAndLabelButton *shareButton;
@property (nonatomic, strong) UIButton *consultButton;
//tableview属性
@property (nonatomic, strong) UITableView *tableView;
//轮播图放大之后的背景图
@property (nonatomic, strong) UIView *backgroundView;
//房评数据
@property (nonatomic, strong) NSMutableArray *dataArray;
@property (nonatomic, strong) MBProgressHUD *hud;
@property (nonatomic, strong) RentHouseDetailModel *model;

@property (nonatomic, strong) SDCycleScrollView *cycleScrollView;
@property (nonatomic, strong) NSMutableArray *imageArr;

@property (nonatomic, strong) NSArray *similiarArr;

@end

@implementation RentHouseDetailViewController

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    self.tabBarController.tabBar.hidden = YES;
}

#pragma mark - 主程序入口
- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    self.automaticallyAdjustsScrollViewInsets = NO;
    //顶部视图
    _myBar = [[BaseTitleNavigationBar alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, 64) WithTitleStr:_model.title];
    [self.view addSubview:_myBar];
    //返回视图添加手势 用于返回
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(back:)];
    [_myBar.leftView addGestureRecognizer:tap];
    //tableview
    [self initTableView];
    //底部视图
    [self initBottomView];
    //菊花
    _hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    _hud.label.text = @"正在加载数据";
    _hud.backgroundView.style = MBProgressHUDBackgroundStyleSolidColor;
    _hud.backgroundView.backgroundColor = [UIColor whiteColor];
    _hud.bezelView.style = MBProgressHUDBackgroundStyleBlur;
    _hud.animationType = MBProgressHUDAnimationZoomIn;
    //数据加载
    [self handleMainData];
    
    // Do any additional setup after loading the view.
}
#pragma mark - 数据处理
//数据处理
- (void)handleMainData {
    _imageArr = [NSMutableArray array];
    _dataArray = [NSMutableArray array];
    _similiarArr = [NSArray array];
    [NetRequest getWithURLString:@"http://aizufang.hrbzjwl.com/tp/api.php/iosapp/erx/" parameters:@{@"itemid": _itemid, @"type": @"1", @"uid": [UserInfoManager sharedManager].uid} progress:^(NSProgress *progress) {
    } success:^(id response) {
        //返回参数判断
        if ([response[@"flag"] isEqualToString:@"1"]) {
            _hud.label.text = @"加载成功";
            [_hud hideAnimated:YES afterDelay:1];
            _similiarArr = response[@"gc"];
            
            NSDictionary *dic = response[@"chuzu"];
            //是否关注
            if ([[dic[@"follow"] description] isEqualToString:@"0"]) {
                _attentionButton.logoImage.image = [UIImage imageNamed:@"cancelAttention"];
            }else {
                _attentionButton.logoImage.image = [UIImage imageNamed:@"attentionSuccess"];
            }
            //标题设置
            _model = [RentHouseDetailModel modelWithDic:dic];
            _myBar.titleLabel.text = _model.title;
            //轮播图赋值 先判断后台给的类型 NSNull类型的话就说明没有图片
            if ([dic[@"thumb"] isKindOfClass:[NSNull class]]) {
                
            }else {
                NSArray *iamgeArr = dic[@"thumb"];
                for (NSDictionary *imageDic in iamgeArr) {
                    [_imageArr addObject:imageDic[@"thumb"]];
                }
            }
            _cycleScrollView.imageURLStringsGroup = _imageArr;
            //经纪人房评数据
            NSDictionary *remarkDic = dic[@"remark"];
            UnfoldModel *model = [[UnfoldModel alloc]init];
            if ([remarkDic[@"intorduce"] isKindOfClass:[NSNull class]]) {
                model.contextStr = @"暂无评论";
            }else {
                model.contextStr = remarkDic[@"intorduce"];
            }
            model.isFold = NO;//给出初始值
            UnfoldFrameModel *frameModel = [[UnfoldFrameModel alloc]init];
            frameModel.model = model;
            [self.dataArray addObject:frameModel];
            
            //刷新UI
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                [_tableView reloadData];
                [MineHistoryManager storeItemID:_itemid withType:5];
            });
        }else {
            _hud.label.text = @"加载失败";
            [_hud hideAnimated:YES afterDelay:1];
        }
    } failure:^(NSError *error) {
        _hud.label.text = @"服务器异常";
        [_hud hideAnimated:YES afterDelay:1];
    }];
}



#pragma mark - 底部视图
/* 底部按钮设置 */
- (void)initBottomView {
    UIView *superView = self.view;
    //底部视图上面的横线
    UIView *topView = [[UIView alloc] init];
    [self.view addSubview:topView];
    //分享、关注中间的竖线
    UIView *midView = [[UIView alloc] init];
    [self.view addSubview:midView];
    //分享 关注
    _attentionButton = [[ImageViewAndLabelButton alloc] init];
    _attentionButton.logoNameLabel.text = @"关注";
    [self.view addSubview:_attentionButton];
    [_attentionButton addTarget:self action:@selector(btn:) forControlEvents:UIControlEventTouchUpInside];
    _attentionButton.tag = 1;
    _shareButton = [[ImageViewAndLabelButton alloc] init];
    _shareButton.logoNameLabel.text = @"分享";
    _shareButton.tag = 2;
    [self.view addSubview:_shareButton];
    [_shareButton addTarget:self action:@selector(btn:) forControlEvents:UIControlEventTouchUpInside];
    _shareButton.logoImage.image = [UIImage imageNamed:@"shareHouse"];
    _consultButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [self.view addSubview:_consultButton];
    //视图布局
    CGFloat width = kScreenWidth / 4;
    [topView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(superView.mas_left);
        make.bottom.equalTo(_attentionButton.mas_top);
        make.height.equalTo(@1);
        make.width.mas_equalTo(kScreenWidth / 2 + 1);
    }];
    topView.backgroundColor = [UIColor colorWithRed:0.8 green:0.8 blue:0.8 alpha:1.0];
    [midView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(_attentionButton.mas_right);
        make.width.equalTo(@1);
        make.height.equalTo(@40);
        make.centerY.equalTo(_attentionButton.mas_centerY);
    }];
    midView.backgroundColor = [UIColor colorWithRed:0.902 green:0.902 blue:0.902 alpha:1.0];
    
    [_attentionButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(superView.mas_left);
        make.bottom.equalTo(superView.mas_bottom);
        make.height.equalTo(@59);
        make.width.mas_equalTo(width);
    }];
    [_shareButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(midView.mas_right);
        make.bottom.equalTo(superView.mas_bottom);
        make.height.equalTo(@59);
        make.width.mas_equalTo(width);
    }];
    
    [_consultButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.equalTo(superView.mas_right);
        make.height.equalTo(@60);
        make.left.equalTo(_shareButton.mas_right);
        make.bottom.equalTo(superView.mas_bottom);
    }];
    _consultButton.backgroundColor = [UIColor colorWithRed:1.0 green:0.502 blue:0.0 alpha:1.0];
    [_consultButton setTitle:@"咨询客服" forState:UIControlStateNormal];
    [_consultButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [_consultButton addTarget:self action:@selector(btn:) forControlEvents:UIControlEventTouchUpInside];
    _consultButton.titleLabel.font = [UIFont systemFontOfSize:20 weight:20];
    
}
//底部按钮点击事件
- (void)btn:(ImageViewAndLabelButton *)button {
    //关注
    if (button.tag == 1) {
        [self attentionHouseActionWithAttentionButton:button];
    }//分享
    else if (button.tag == 2) {
        //如果需要分享回调，请将delegate对象设置self，并实现下面的回调方法
        [UMSocialData defaultData].extConfig.title = @"爱租房，找房就是找生活";
        //微信
        [UMSocialData defaultData].extConfig.wechatSessionData.shareImage = [UIImage imageNamed:@"appIcon"];
        [UMSocialData defaultData].extConfig.wechatSessionData.url = [NSString stringWithFormat:@"http://aizufang.hrbzjwl.com/tp/index.php/Home/center/dicesecon/id/%@", _itemid];
        //朋友圈
        [UMSocialData defaultData].extConfig.wechatTimelineData.shareImage = [UIImage imageNamed:@"appIcon"];
        [UMSocialData defaultData].extConfig.wechatTimelineData.url = [NSString stringWithFormat:@"http://aizufang.hrbzjwl.com/tp/index.php/Home/center/dicesecon/id/%@", _itemid];
        //QQ
        [UMSocialData defaultData].extConfig.qqData.url = [NSString stringWithFormat:@"http://aizufang.hrbzjwl.com/tp/index.php/Home/center/dicesecon/id/%@", _itemid];
        [UMSocialData defaultData].extConfig.qqData.shareImage = [UIImage imageNamed:@"appIcon"];
        //QQ空间
        [UMSocialData defaultData].extConfig.qzoneData.url = [NSString stringWithFormat:@"http://aizufang.hrbzjwl.com/tp/index.php/Home/center/dicesecon/id/%@", _itemid];
        [UMSocialData defaultData].extConfig.qzoneData.shareImage = [UIImage imageNamed:@"appIcon"];
        
        
        //微博
        [UMSocialData defaultData].extConfig.sinaData.shareImage = [UIImage imageNamed:@"appIcon"];
        
        [UMSocialSnsService presentSnsIconSheetView:self
                                             appKey:@"57cfcf67e0f55aaf9e002512"
                                          shareText:@"爱租房是一款集租房、买房、二手房交易为一体的APP，随时随地找房，世界从此不陌生"
                                         shareImage:[UIImage imageNamed:@"icon"]
                                    shareToSnsNames:@[UMShareToWechatSession,UMShareToWechatTimeline,UMShareToSina,UMShareToQQ, UMShareToQzone]
                                           delegate:self];
    }
    //联系客服
    else {
        NSMutableString *str=[[NSMutableString alloc] initWithFormat:@"telprompt://%@",unifyServiceNumber];
        [[UIApplication sharedApplication] openURL:[NSURL URLWithString:str]];
    }
}
#pragma mark - 关注房源
- (void)attentionHouseActionWithAttentionButton:(ImageViewAndLabelButton *)button {
    if ([self isLogin]) {
        NSDictionary *submitDic = @{@"uid": [UserInfoManager sharedManager].uid, @"fid": _itemid, @"type": @"1"};
        [NetRequest getWithURLString:@"http://aizufang.hrbzjwl.com/tp/index.php/Api/iosapp/follow_app/" parameters:submitDic progress:^(NSProgress *progress) {
            
        } success:^(id response) {
            if ([response[@"flag"] isEqualToString:@"1"]) {
                button.logoImage.image = [UIImage imageNamed:@"cancelAttention"];
                [self alertMessage:@"取消关注"];
            }else if ([response[@"flag"] isEqualToString:@"2"]) {
                button.logoImage.image = [UIImage imageNamed:@"attentionSuccess"];
                [self alertMessage:@"关注成功"];
            }else {
                [self alertMessage:@"操作失败"];
            }
        } failure:^(NSError *error) {
            
        }];
    }else {
        MineLoginViewController *mineVC = [[MineLoginViewController alloc] init];
        [self.navigationController pushViewController:mineVC animated:YES];
    }
}
//用户提示框
- (void)alertMessage:(NSString *)message {
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:nil message:message preferredStyle:UIAlertControllerStyleAlert];
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [self dismissViewControllerAnimated:YES completion:nil];
    });
    [self presentViewController:alertController animated:YES completion:nil];
}

#pragma mark - tableView
- (void)initTableView {
    _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 64, kScreenWidth, kScreenHeight - 124) style:UITableViewStylePlain];
    [self.view addSubview:_tableView];
    _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    _tableView.delegate = self;
    _tableView.dataSource = self;
    [_tableView registerClass:[ReuseHouseBaseInfoTableViewCell class] forCellReuseIdentifier:NSStringFromClass([ReuseHouseBaseInfoTableViewCell class])];
    [_tableView registerClass:[SecondaryHouseDetailTableViewCell class] forCellReuseIdentifier:NSStringFromClass([SecondaryHouseDetailTableViewCell class])];
    [_tableView registerClass:[IndoorMatchTableViewCell class] forCellReuseIdentifier:NSStringFromClass([IndoorMatchTableViewCell class])];
    [_tableView registerClass:[HouseEvaluateTableViewCell class] forCellReuseIdentifier:NSStringFromClass([HouseEvaluateTableViewCell class])];
    [_tableView registerClass:[SecondaryHouseListNoSlideTableViewCell class] forCellReuseIdentifier:NSStringFromClass([SecondaryHouseListNoSlideTableViewCell class])];
    [_tableView registerClass:[HouseDetailCharacteristicTableViewCell class] forCellReuseIdentifier:NSStringFromClass([HouseDetailCharacteristicTableViewCell class])];
    //顶部轮播图
    _cycleScrollView = [SDCycleScrollView cycleScrollViewWithFrame:CGRectMake(0, 0, kScreenWidth, 170) imageURLStringsGroup:_imageArr];
    _cycleScrollView.delegate = self;
    _cycleScrollView.placeholderImage = [UIImage imageNamed:@"placeHolderPic"];
    _tableView.tableHeaderView = _cycleScrollView;
    
}
//行数
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return 9;
}

//行高
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
        if (indexPath.row == 0) {
            return 120;
        }else if (indexPath.row == 2) {
            return 30;
        }else if (indexPath.row == 3) {
            return 180;
        }else if (indexPath.row == 5) {
            return 25;
        }else if (indexPath.row == 6) {
            return 100;
        }else if (indexPath.row == 8) {
            UnfoldFrameModel *frameModel = [self.dataArray firstObject];
            return frameModel.cellHeight;
        }else {
            return 5;
        }
}
//cell
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
        if (indexPath.row == 0) {
            ReuseHouseBaseInfoTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass([ReuseHouseBaseInfoTableViewCell class])];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            cell.model = _model;
            cell.priceNameLabel.text = @"售价";
            return cell;
        }else if (indexPath.row == 2) {
            HouseDetailCharacteristicTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass([HouseDetailCharacteristicTableViewCell class])];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            cell.model = _model;
            return cell;
            
        }else if (indexPath.row == 3) {
            SecondaryHouseDetailTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass([SecondaryHouseDetailTableViewCell class])];
            cell.model = _model;
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            return cell;
            
        }else if (indexPath.row == 6) {
            SecondaryHouseListNoSlideTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass([SecondaryHouseListNoSlideTableViewCell class])];
            NSDictionary *dic = [_similiarArr firstObject];
            SecondaryListModel *model = [SecondaryListModel modelWithDic:dic];
            cell.model = model;
            cell.tag = [model.itemid integerValue];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            return cell;
        }else if (indexPath.row == 8) {
            HouseEvaluateTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass([HouseEvaluateTableViewCell class])];
            cell.remarkDic = _model.remark;
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            //2,设置cell的数据
            UnfoldFrameModel *frameModel = [self.dataArray firstObject];
            cell.frameModel = frameModel;
            cell.delegate = self;
            return cell;
        }
        else {
            static NSString *cellID = @"cellID";
            UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellID];
            if (!cell) {
                cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:cellID];
            }
            if (indexPath.row == 5) {
                cell.contentView.backgroundColor = [UIColor whiteColor];
                ;
                cell.textLabel.text = @"相似房源";
            }else {
                cell.contentView.backgroundColor = [UIColor colorWithRed:0.9528 green:0.9435 blue:0.962 alpha:1.0];
                ;
            }
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            return cell;
        }
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.row == 6) {
        SecondaryHouseListNoSlideTableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
        RentHouseDetailViewController *detailVC = [[RentHouseDetailViewController alloc] init];
        detailVC.itemid = [NSString stringWithFormat:@"%ld", (long)cell.tag];
        [self.navigationController pushViewController:detailVC animated:YES];
    }
}
#pragma mark - 点击事件

//返回手势
- (void)back:(UITapGestureRecognizer *)tap {
    [self.navigationController popViewControllerAnimated:YES];
}
#pragma mark - VC delegate
//隐藏 展开文本
-(void)UnfoldCellDidClickUnfoldBtn:(UnfoldFrameModel *)frameModel
{
    UnfoldModel *model = frameModel.model;
    model.isFold = !model.isFold;
    frameModel.model = model;//这句话很关键，要把值设置回来，因为其setModel方法中会重新计算frame
    [_tableView reloadData];
}


//拨打经纪人电话 如果经纪人没有电话的话 直接联系客服
- (void)callAgentPhoneNumber {
    if ([_model.remark[@"mobile"] isKindOfClass:[NSNull class]]) {
        NSMutableString *str=[[NSMutableString alloc] initWithFormat:@"telprompt://%@",unifyServiceNumber];
        [[UIApplication sharedApplication] openURL:[NSURL URLWithString:str]];
    }else {
        NSMutableString *str=[[NSMutableString alloc] initWithFormat:@"telprompt://%@",_model.remark[@"mobile"]];
        [[UIApplication sharedApplication] openURL:[NSURL URLWithString:str]];
    }
}

- (void)cycleScrollView:(SDCycleScrollView *)cycleScrollView didSelectItemAtIndex:(NSInteger)index {
    //创建SDPhotoBrowser实例
    SDPhotoBrowser *browser = [[SDPhotoBrowser alloc] init];
    browser.sourceImagesContainerView = [_cycleScrollView.subviews firstObject];
    browser.imageCount = _imageArr.count;
    browser.currentImageIndex = index;
    browser.delegate = self;
    [browser show]; // 展示图片浏览器
    
 
}

// 返回临时占位图片（即原来的小图）

- (UIImage *)photoBrowser:(SDPhotoBrowser *)browser placeholderImageForIndex:(NSInteger)index {
    UIImage *myImage = [UIImage imageNamed:@"placeHolderPic"];
    return myImage;
}

// 返回高质量图片的url

- (NSURL *)photoBrowser:(SDPhotoBrowser *)browser highQualityImageURLForIndex:(NSInteger)index {
    NSURL *picUrl = [NSURL URLWithString:_imageArr[index]];
    return picUrl;
}

@end
